package com.neusoft.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.neusoft.model.BooksModel;
import com.neusoft.model.entity.Appointment;
import com.neusoft.model.entity.Books;
import com.neusoft.model.entity.Borrow_history;
import com.neusoft.model.entity.User;
import com.neusoft.model.vo.BooksModelVO;
import com.neusoft.service.AppointmentService;
import com.neusoft.service.BooksService;
import com.neusoft.service.HistoryService;

@Controller
@RequestMapping("/books")
public class BooksController {

	@Autowired
	BooksService booksService;

	@Autowired
	AppointmentService appointmentService;
	
	@Autowired
	HistoryService historyService;
	
	@RequestMapping("/query")
	private String queryBooks(BooksModelVO booksModelVO, Model model) {
		BooksModel booksModel = booksService.findBooksByVo(booksModelVO);
		model.addAttribute("booklist", booksModel.getRows());

		return "booklist";
	}

	@RequestMapping("/queryrtjson")
	@ResponseBody
	private BooksModel queryBooksRtJson(BooksModelVO booksModelVO, Model model) {
		// 判断booksModel是否为空
		if (booksModelVO == null) {
			booksModelVO = new BooksModelVO();
		}
		BooksModel booksModel = booksService.findBooksByVo(booksModelVO);
		// 返回书籍的总数量s
		booksModel.setTotal(booksModel.getRows().size());
		model.addAttribute("booklist", booksModel.getRows());

		return booksModel;
	}

	// 测试用的
	@RequestMapping("/tomanage")
	private String toManage() {
		return "manage";
	}

	//返回easyui的json数据
	@RequestMapping("/queryrtjson_eu")
	@ResponseBody
	private BooksModel queryBooksRtJsonEU(BooksModelVO booksModelVO,
			Model model, int page, int rows) {
		// 判断booksModel是否为空
		if (booksModelVO == null) {
			booksModelVO = new BooksModelVO();
		}
		BooksModel booksModel = booksService.findBooksByVoEU(booksModelVO,
				page, rows);
		return booksModel;
	}
	
	@RequestMapping("/toqueryup")
	private String toQueryUp() {
		return "booklistup";
	}
	
	
	
	
	
	
	@RequestMapping("/toquery")
	private String queryBooks(String strSearchType,String strText,Model model){
		System.out.println(strSearchType+"f"+strText);
		BooksModel booksModel =new BooksModel();
		BooksModelVO booksModelVO=new BooksModelVO();
		if(strSearchType.equals("bookname")){
			booksModel.setBookName(strText);
		}else if(strSearchType.equals("author")){
			booksModel.setAuthor(strText);
		}else if(strSearchType.equals("isbn")){
			booksModel.setIsbn(strText);
		}else if(strSearchType.equals("callno")){
			booksModel.setCallno(strText);
		}else if(strSearchType.equals("publisher")){
			
			booksModel.setPublish(strText);
		}
		booksModelVO.setBooksModel(booksModel);
		BooksModel booksModel2=booksService.findBooksByVo(booksModelVO);
		
		for(int i=0;i<booksModel2.getRows().size();i++)
			System.out.println(booksModel2.getRows().get(i).getId()+"ee");
		
		List<BooksModel> distinguish1=booksService.distinguish(booksModel2);
//		System.out.println(distinguish1.get(0).getCallno()+"df");
		model.addAttribute("booklist",distinguish1);
		
		if(strSearchType.equals("callno")){
		model.addAttribute("searchType","索书号");
		}else if(strSearchType.equals("bookname")){
			model.addAttribute("searchType","书名");
			}else if(strSearchType.equals("author")){
				model.addAttribute("searchType","作者");
			} else if(strSearchType.equals("isbn")){
				model.addAttribute("searchType","ISBN");
			}else if(strSearchType.equals("publisher")){
				model.addAttribute("searchType","出版社");
			}
		model.addAttribute("searchText",strText);
		model.addAttribute("numOfResult",distinguish1.size());
//		System.out.println(booksModel2.getRows().get(0).getDeadline())
		return "queryresult";
	}



	@RequestMapping("/mylibrary")
	private String displayOwnLibrary(BooksModelVO booksModelVO,Model model){
//		System.out.println(session.getAttribute("user"));
//		System.out.println(((User)model.getAttribute("user")).getId());
//		BooksModel booksModel=booksService.findBooksByVo(booksModelVO);
//		model.addAttribute("booklist", booksModel.getRows());
		
		return "mylibrary";
	}
	
	@RequestMapping("/bookitem")
	private String displayItems(BooksModelVO booksModelVO,Model model){
//		for(int i=0;i<10000;i++)
//		System.out.println("mylibrary2");
//		BooksModel booksModel=booksService.findBooksByVo(booksModelVO);
//		model.addAttribute("booklist", booksModel.getRows());
//		System.out.println("aut "+booksModelVO.getBooksModel().getAuthor());
//		BooksModel booksModel =new BooksModel();
//		BooksModelVO booksModelVO=new BooksModelVO();
		
			
		BooksModel booksModel2=booksService.findBooksByCallno(booksModelVO);
//		Syste,\
			
//			int numOfBorrowAbled=booksModel4.getRows().size();
//			int numOfAtLibrary
			
		booksService.updateStatus(booksModel2);
//		List<BooksModel> booksModels=new ArrayList<BooksModel>();
//		for(Books books:booksModel2.getRows()){
//			booksModels.add(books);
//		}
		model.addAttribute("bookInfo", booksModel2.getRows());
		model.addAttribute("book_id", booksModel2.getRows().get(0).getId());
//		model.addAttribute("bookInfo", booksModel2);
//		System.out.println(booksModel2.getRows().get(0).getAuthor());
		return "bookitem";
	}
	
	@RequestMapping("/appointment")
	private String appointmentApply(HttpSession session,String book_id,Model model){
		if(book_id.isEmpty()){
			model.addAttribute("isNull",1);
			return "appointment";
		}
		BooksModel booksModel =new BooksModel();
		BooksModelVO booksModelVO=new BooksModelVO();
		 
//		int userId=Integer.valueOf(((User)session.getAttribute("user")).getId());
			booksModel.setId(Integer.valueOf(book_id));
//			System.out.println(userId+"ids"); 
			System.out.println(book_id+"idss"); 
		booksModelVO.setBooksModel(booksModel);
		Books books=booksService.findBooksByID(booksModelVO);
		String callno=books.getCallno();
		String bookName=books.getBookName();
		String author=books.getAuthor();
		System.out.println(callno+"no");
//		System.out.println(((User)session.getAttribute("user")).getId());
//		AppointmentsModelVO appointmentsModelVO=new AppointmentsModelVO();
//		AppointmentsModel appointmentsModel=new AppointmentsModel();
//		appointmentsModel.setBookingId(Integer.valueOf(book_id));
//		appointmentsModelVO.setAppointmentsModel(appointmentsModel);
		
		Appointment appointment=new Appointment();
		
		appointment.setId(((User)session.getAttribute("user")).getId());
		appointment.setBookingId(Integer.valueOf(book_id));
//		appointment.setId((String)session.getAttribute("user"));
//		appointment.setId("33");
		 appointment.setCallno(callno);
		 appointment.setAuthor(author);
		 appointment.setBookName(bookName);
		Date d = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String currdate = format.format(d);
		
		appointment.setAppointmentTime(d);
        Calendar ca = Calendar.getInstance();
	        ca.add(Calendar.DATE, 6);// num为增加的天数，可以改变的
		        d = ca.getTime();
			      
			       
		booksService.updateStatusToTwo(Integer.valueOf(book_id));
		appointment.setDeadline(d);
		
		appointmentService.insertAppointment(appointment); 
		model.addAttribute("isNull",0);
		return "appointment";
	}
	
	
	
	
	
	
	
	@RequestMapping("/insert")
	public String insert(BooksModelVO booksModelVO,HttpServletRequest req){
		booksService.insertBooks(booksModelVO);
		req.setAttribute("sucessMess", "插入成功");
		return "insert";
	}
	
	@RequestMapping("/imformation")
	public String imformation(HttpServletRequest req){
		BooksModel booksModel=booksService.findAllBooks();
		req.setAttribute("bookList", booksModel.getRows());
		req.setAttribute("size", booksModel.getRows().size());
		
		return "/imformation.jsp";
		
	}
	
	
	
	@RequestMapping("/toinsert")
	private String toInsert(){		
		return "insert";
	}
	
	@RequestMapping("/toedit")
	private String toEdit(int id, Model model,HttpServletRequest req){	
		id = Integer.valueOf(id);
		Books book=booksService.findBooksbyID(id);
		Date inTime = book.getInTime();
		SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
		if(book.getLendTime()!=null){
			Date lendTime = book.getLendTime();
			String lendTimestr = formater.format(lendTime);
			model.addAttribute("lendTime",lendTimestr);
		}
		if(book.getDeadline()!=null){
			Date deadline = book.getDeadline();
			String deadlinestr = formater.format(deadline);
			model.addAttribute("deadline",deadlinestr);
		}
		
		String inTimestr = formater.format(inTime);
		model.addAttribute("inTime",inTimestr);
		model.addAttribute("book", book);
		return "edit";
	}
	
	@RequestMapping("/back")
	private String back(String id){		
		return "redirect:/user/tomanage.action?id="+id;
	}
	
	@RequestMapping("/edit")
	private String Edit(Books books,HttpServletRequest req ,Model model){
		if(books.getBorrower()!=""){
			if(books.getStatus()==0){
				//可借
				books.setStatus(1);
				booksService.updateBooksbyID(books);
				req.setAttribute("sucessMess", "修改成功");
			}else if(books.getStatus()==2||books.getStatus()==3){
				//判断是否为预约人
				Appointment appointment=appointmentService.findAppointmentByBookID(books.getId());
				if(appointment.getId().equals(books.getBorrower())){
					//可以借
					books.setStatus(1);
					booksService.updateBooksbyID(books);
					appointmentService.deleteAppointmentByBookID(books.getId());
					req.setAttribute("sucessMess", "修改成功");
				}else{
					
					req.setAttribute("sucessMess", "该书以被其他人预约！不可借！");
				}
			}
		}else{
			if(books.getStatus()==1){//未预约
				books.setStatus(0);
			}else {
				books.setStatus(3);
			}
			
			booksService.updateBooksbyID(books);
			req.setAttribute("sucessMess", "修改成功");
		}
		
//		booksService.findBooksByActiveId()
//		booksService.updateBooksbyID(books);
		Date inTime = books.getInTime();
		SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
		if(books.getLendTime()!=null){
			Date lendTime = books.getLendTime();
			String lendTimestr = formater.format(lendTime);
			req.setAttribute("lendTime",lendTimestr);
		}
		if(books.getDeadline()!=null){
			Date deadline = books.getDeadline();
			String deadlinestr = formater.format(deadline);
			req.setAttribute("deadline",deadlinestr);
		}
		
		String inTimestr = formater.format(inTime);
		
		req.setAttribute("inTime",inTimestr);
		if(books.getBorrower()!=""){
			Borrow_history history = new Borrow_history();
			history.setId(books.getBorrower());
			history.setBookId(books.getId());
			historyService.insertHistory(history);
		}
		
		model.addAttribute("book",books);
		return "edit";
		
	}
	
	@RequestMapping("/delete")
	private String Delete(String bookid,String adminid ){
		Integer bookID= Integer.valueOf(bookid);
		booksService.deleteBooksbyID(bookID);
		return "redirect:/user/tomanage.action?id="+adminid;
	}
	
}
